package zhxt.helmet.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import zhxt.helmet.pojo.*;
import zhxt.helmet.service.PopedomService;

import java.util.ArrayList;
import java.util.List;

//辖区控制器，用于从辖区id获取名字，或根据上级辖区获取下级辖区
@Controller
@RequestMapping("/popedom")
public class PopedomController {
    @Autowired
    private PopedomService popedomService;

    @RequestMapping(value = "/getProvinces", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getProvinces(@SessionAttribute("user") User user) throws JsonProcessingException {
        List<Province> provinceList=popedomService.getProvinces(user);
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();
        // 将 List<Province> 转换为 JSON 字符串
        return objectMapper.writeValueAsString(provinceList);
    }

    //选择省后，初始化市列表
    @RequestMapping(value = "/getCitiesByProvinceId", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCitiesByProvinceId(@RequestParam("provinceId") int provinceId,
                                        @SessionAttribute("user") User user) throws JsonProcessingException {
        List<City> cityList =  popedomService.getCitiesByProvinceId(provinceId, user);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(cityList);
    }

    //选择市后，初始化区列表
    @RequestMapping(value = "/getDistrictsByCityId", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getDistrictsByCityId(@RequestParam("cityId") int cityId,
                                        @SessionAttribute("user") User user) throws JsonProcessingException {
        List<District> districtList =  popedomService.getDistrictsByCityId(cityId, user);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(districtList);
    }

    //选择区后，初始化块列表
    @RequestMapping(value = "/getBlocksByDistrictId", produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getBlocksByDistrictId(@RequestParam("districtId") int districtId,
                                        @SessionAttribute("user") User user) throws JsonProcessingException {
        List<Block> blockList =  popedomService.getBlocksByDistrictId(districtId, user);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(blockList);
    }

}
